package models

import (
	"errors"
	"time"

	"github.com/jinzhu/gorm"
)

// 模板收藏 结构体定义
type TemplateOperate struct {
	Id         int        `gorm:"column:id"`
	Uid        int        `gorm:"column:uid"`
	OperateUid int        `gorm:"column:operate_uid"`
	Action     int        `gorm:"column:action"`
	TeId       int        `gorm:"column:te_id"`
	Status     int        `gorm:"column:status"`
	Createtime int64      `gorm:"column:create_time"`
	Updatetime int64      `gorm:"column:update_time"`
	Template   []Template `gorm:"foreignKey:TeId;references:Id"`
}

// 模板收藏 结构体定义
type templateOperate struct {
	Id       int      `json:"id"`
	Uid      int      `json:"uid"`
	TeId     int      `json:"te_id"`
	Status   int      `json:"status"`
	Template template `gorm:"foreignKey:TeId;references:Id"`
}

// handleDBError 处理数据库操作错误
func handleDBError(result *gorm.DB) (int, error) {
	if result.Error != nil {
		return 0, result.Error
	}
	return 0, nil
}

func AddTemplateCollect(uid int, operate_uid int, te_id int, action int) (int, error) {
	var templateCollect TemplateOperate

	timestamp := time.Now().Unix()
	// 先根据 uid、te_id 和 action 查询记录
	result := db.Where("uid = ? AND te_id = ?", uid, te_id).First(&templateCollect)

	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		// 记录不存在，进行新增操作
		templateCollect = TemplateOperate{
			Uid:        uid,
			OperateUid: operate_uid,
			Action:     action,
			TeId:       te_id,
			Status:     1,
			Createtime: timestamp,
			Updatetime: timestamp,
		}
		result = db.Create(&templateCollect)
		if _, err := handleDBError(result); err != nil {
			return 0, err
		}
		return 1, nil
	}

	if result.Error != nil {
		// 其他错误，直接返回
		return 0, result.Error
	}

	// 记录存在，根据 status 状态进行修改
	var status = 0
	if templateCollect.Status == 0 {
		templateCollect.Status = 1
		status = 1
	} else {
		templateCollect.Status = 0
		status = 2
	}
	templateCollect.Updatetime = timestamp
	result = db.Save(&templateCollect)
	if _, err := handleDBError(result); err != nil {
		return 0, err
	}
	return status, nil
}

// GetTemplateList 查询模板列表
// GetMyCollectedTemplates 获取用户收藏的模板列表
func GetMyCollectedTemplates(uid int, title string, page int, pageSize int) ([]templateOperate, error) {

	var templates []templateOperate
	query := db.Preload("Template").Select("md_template.id,md_template.uid,te_id,md_template.status").Where("md_template.uid = ? AND md_template.status = ?", uid, 1).Order("md_template.id desc")

	// // 根据 title 进行模糊查询
	if title != "" {
		query = query.Joins("JOIN md_template ON md_template_operate.te_id = md_template.id").
			Where("md_template.title LIKE ?", "%"+title+"%")
	}

	// 分页查询
	query = query.Limit(page).Offset(pageSize)

	result := query.Find(&templates)
	if result.Error != nil {
		return nil, result.Error
	}

	return templates, nil
}
